/********************************************************************************
 *	Copyright 2011 Gerry Weirich
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at 
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *
 *	$Id$
 ********************************************************************************/

package ch.rgw.cybert
import org.codehaus.jackson.annotate._
import scala.collection.JavaConversions._

/**
 * The resource object contains all questions and configuration information
 * @author gerry
 *
 */
object NodeRsc {
  val jacksonID = "CybertResources-2011";
}

class NodeRsc {
  private var rev: String = null;
  private[cybert] var questions = Map[Int, String]()

  @JsonProperty("_id")
  def getIdentification = NodeRsc.jacksonID;

  // Dummy to make couchDB happy
  @JsonProperty("_id")
  def setIdentification(s: String) = {}

  @JsonProperty("_rev")
  def getRevision(): String = {
    return rev;
  }

  @JsonProperty("_rev")
  def setRevision(nrev: String) {
    rev = nrev;
  }

  /**
   * insert a new question to the persisted collection of questions
   * @param text the QUestuin to add. If the same Question exists already: do nothing
   * @return the handle of the newly added or found question. The handle can be used to
   * retrieve the question later.
   */
  def findOrAddQuestion(text: String): Int = {
    questions.foreach(q => if (q._2.equals(text)) return q._1);
    val handle = text.hashCode;
    questions += (handle -> text)
    handle;
  }
  /**
   * retrieve a question with its handle
   * @param qhandle the handle
   * @return an Option withe Some(question) or None.
   */
  def getQuestion(qhandle: Int) = questions.get(qhandle)
  
  /**
   * get all persisted questions 
   * @return a java hashmap with <handle,String>
   */
  def getQuestions: java.util.HashMap[Int, String] = {
    val ret = new java.util.HashMap[Int, String]();
    questions.foreach { q => ret.put(q._1, q._2) }
    return ret;
  }
  
  // needed to make ektorp happy
  def setQuestions(qq: java.util.HashMap[Int, String]) = questions = Map[Int, String]() ++ qq;

  private[cybert] def merge(other: NodeRsc) = {
    other.questions.foreach { q =>
      questions.add(q._1, q._2);
    }
    rev = other.rev;
  }
}